package org.eclipseuseradmin.ui.utils;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.widgets.Text;

public class DialogSupport {

	private List<Message> messages = new ArrayList<Message>();
	
	private Message currentMessage;

	private Text messageText;

	public DialogSupport(Text messageText) {
		this.messageText = messageText;
	}

	public void addMessage(Object key, String value) {

		Message message = getMessage(key);
		message.value = value;

		currentMessage = getCurrentMessage();
		messageText.setText(currentMessage.value);
	}

	public void removeMessage(Object key) {

		Message message = getMessage(key);
		message.value = null;

		currentMessage = getCurrentMessage();
		if (currentMessage != null) {
			messageText.setText(currentMessage.value);
		} else {
			messageText.setText("");
		}
	}

	private Message getMessage(Object key) {

		for (Message message : messages) {
			if (message.key.equals(key)) {
				return message;
			}
		}
		Message message = new Message(key, null);
		messages.add(message);
		return message;
	}

	private Message getCurrentMessage() {
		for (Message message : messages) {
			if (message.value != null) {
				return message;
			}
		}
		return null;
	}

	public void removeAll() {

		messages.clear();
		messageText.setText("");
	}

	public boolean isMessage() {
		return currentMessage != null;
	}

	private class Message {

		public Object key;

		public String value;

		public Message(Object key, String value) {
			this.key = key;
			this.value = value;
		}

		@Override
		public boolean equals(Object obj) {

			if (!(obj instanceof Message)) {
				return false;
			}

			Message message = (Message) obj;
			return this.key.equals(message.key);
		}

	}
}
